package com.spring;

import java.io.*;
import java.net.*;

public class Client1_tcp {
    public static void main(String[] args) {
        try (Socket socket = new Socket("127.0.0.1", 12345)) {
            System.out.println("已连接服务器，可以开始聊天 (输入 exit 退出)");

            // 接收消息的线程
            new Thread(() -> {
                try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                    String msg;
                    while ((msg = in.readLine()) != null) {
                        System.out.println("[对方] " + msg);
                    }
                } catch (IOException e) {
                    System.out.println("服务器关闭连接");
                }
            }).start();

            // 发送消息
            try (BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
                String input;
                while ((input = console.readLine()) != null) {
                    if ("exit".equalsIgnoreCase(input)) break;
                    out.println(input);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
